package com.campus.notice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.api.util.UserContext;
import com.campus.common.result.Result;
import com.campus.common.student.mapper.StudentMapper;
import com.campus.common.teacher.mapper.TeacherMapper;
import com.campus.common.user.mapper.AuthMapper;
import com.campus.course.dto.entity.CourseRecords;
import com.campus.course.mapper.CourseRecordsMapper;
import com.campus.notice.entity.Message;
import com.campus.notice.mapper.MessageMapper;
import com.campus.notice.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 消息通知表 服务实现类
 * </p>
 *
 * @author maojr
 * @since 2024-11-18
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private CourseRecordsMapper courseRecordsMapper;

    @Autowired
    private AuthMapper authMapper;

    @Override
    public void acceptExamination(Message message) {
        messageMapper.insert(message);
    }

    @Override
    public Result arrangeExamination(int courseId, String content) {
        //获取发送者ID
        int userId = UserContext.getUserId();

        //收获该课程下的所有学生
        List<CourseRecords> courseRecordsList = courseRecordsMapper.selectList(
                new QueryWrapper<CourseRecords>().eq("course_id", courseId)
        );
        //分发信息到每个学生
        for (CourseRecords stu : courseRecordsList) {
            Message message = new Message();
            message.setAccepterId(studentMapper.selectById(stu.getStudentId()).getUserId());
            message.setSendTime(LocalDateTime.now());
            message.setSenderName(authMapper.selectById(userId).getName());
            message.setContent(content);
            message.setTheme("考试通知.");
            acceptExamination(message);
        }
        return Result.success("安排成功");
    }

    @Override
    public Result stuGetAllMessage() {
        //获取学生用户ID
        int userId = UserContext.getUserId();
        List<Message> messages = messageMapper.selectList(
                new QueryWrapper<Message>().eq("accepter_id", userId)
        );

        return Result.success(messages,"获取信息成功");
    }

    @Override
    public Result stuDeleteMessage(int messageId) {
        if (messageMapper.deleteById(messageId) > 0) {
            return Result.success("删除消息成功");
        }
        return Result.fail("删除消息失败",null);
    }
}
